package com.polaris.live.ui.game

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.LinearLayout
import com.hjq.language.MultiLanguages
import com.just.agentweb.AbsAgentWebSettings
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient
import com.just.agentweb.IAgentWebSettings
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.ServerConfig
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.util.LogExt
import com.polaris.live.common.util.SystemUtils
import com.polaris.live.databinding.GameWebViewBinding
import com.polaris.live.resp.back_resp.GameVo
import com.polaris.live.resp.bean.GameBean
import com.polaris.live.resp.bean.GameLeisureBean
import com.polaris.live.ui.game.js.NativeBridge
import com.polaris.live.ui.game.js.YomiNativeBridge
import com.polaris.live.ui.party.baishun.BaiShunNativeBridge
import com.polaris.live.ui.party.listener.BaiShunListener
import com.polaris.live.utils.route.RouterUtils
import ren.yale.android.cachewebviewlib.WebViewCacheInterceptorInst

/**
 * GameWebView
 * @author Created by 天晴 on 2024/1/15 15:12
 * @since 1.0.0
 **/
class GameWebView(context: Context, attributeSet: AttributeSet? = null) :
    LinearLayout(context, attributeSet) {

    var mAgentWeb: AgentWeb? = null
    var mViewModel: BaseViewModel? = null
    private val mBinding = GameWebViewBinding.inflate(LayoutInflater.from(context), this, true)

    private var nativeBridge: NativeBridge? = null
    private var yomiNativeBridge: YomiNativeBridge? = null
    private var baiShunNativeBridge: BaiShunNativeBridge? = null
    fun initWeb(
        activity: Activity,
        gameVo: GameVo,
        gameMode: String,
        roomId: String,
        recharge: () -> Unit,
        destroy: () -> Unit,
    ) {
        val gameBean =
            GameBean(gameVo, gameMode, getLanguages(gameVo.providerType), roomId, UserManager.getUserId().toString())
        // 开启调试
        if (ServerConfig.isDebug()) {
            WebView.setWebContentsDebuggingEnabled(true)
        }

        val builder = AgentWeb.with(activity)
            .setAgentWebParent(
                mBinding.llContent,
                LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            .closeIndicator()
            .setWebChromeClient(mWebChromeClient)
            .setWebViewClient(webViewClient)
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) //打开其他应用时，弹窗咨询用户是否前往其他应用
            .setMainFrameErrorView(R.layout.widget_item_error, -1)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .interceptUnkownUrl()
            .setAgentWebWebSettings(object : AbsAgentWebSettings() {
                override fun bindAgentWebSupport(agentWeb: AgentWeb?) {
                }

                override fun toSetting(webView: WebView?): IAgentWebSettings<*> {
                    return super.toSetting(webView).apply {
                        setWebSettings(webSettings)
                    }
                }
            })

        mAgentWeb = builder.createAgentWeb()
            .ready()
            .go(if (gameMode == GameUtils.FULL_SCREEN || gameMode == GameUtils.FULL_SCREEN2) gameVo.address else gameVo.halfScreenAddress)
            .apply {
                //yomi游戏
                if (isYomiGame(gameVo.providerType)) {
                    yomiNativeBridge = YomiNativeBridge(activity, gameBean, this, recharge, destroy)
                    //注入对象,与js进行通信 NativeBridge
                    jsInterfaceHolder.addJavaObject("yomi", yomiNativeBridge)
                } else {
                    nativeBridge = NativeBridge(activity, gameBean, this, recharge, destroy)
                    //注入对象,与js进行通信 NativeBridge
                    jsInterfaceHolder.addJavaObject("NativeBridge", nativeBridge)
                }

                if (gameMode == GameUtils.HALF_SCREEN || gameMode == GameUtils.HALF_SCREEN2) {
                    webCreator.webView.setBackgroundColor(Color.TRANSPARENT)
                    webCreator.webParentLayout.setBackgroundColor(Color.TRANSPARENT)
                    mBinding.root.setBackgroundColor(Color.TRANSPARENT)
                }
            }
    }

    /**
     *
     * 休闲游戏
     */
    fun initWebLeisure(
        activity: Activity,
        gameLeisureBean: GameLeisureBean,
        listener: BaiShunListener
    ) {
        // 开启调试
        if (ServerConfig.isDebug()) {
            WebView.setWebContentsDebuggingEnabled(true)
        }

        val builder = AgentWeb.with(activity)
            .setAgentWebParent(
                mBinding.llContent,
                LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            .closeIndicator()
            .setWebChromeClient(mWebChromeClient)
            .setWebViewClient(webViewClient)
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) //打开其他应用时，弹窗咨询用户是否前往其他应用
            .setMainFrameErrorView(R.layout.widget_item_error, -1)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .interceptUnkownUrl()
            .setAgentWebWebSettings(object : AbsAgentWebSettings() {
                override fun bindAgentWebSupport(agentWeb: AgentWeb?) {
                }

                override fun toSetting(webView: WebView?): IAgentWebSettings<*> {
                    return super.toSetting(webView).apply {
                        setWebSettings(webSettings)
                    }
                }
            })
        val url =
            "${gameLeisureBean.url}${if (gameLeisureBean.url.contains("?")) "&" else "?"}loadingBg=0&hallBg=0&gameBg=0"
        mAgentWeb = builder.createAgentWeb()
            .ready()
            .go(url)
            .apply {
                baiShunNativeBridge = BaiShunNativeBridge(activity, gameLeisureBean, this, listener)
                //注入对象,与js进行通信 NativeBridge
                jsInterfaceHolder.addJavaObject("NativeBridge", baiShunNativeBridge)

                webCreator.webView.setBackgroundColor(Color.TRANSPARENT)
                webCreator.webParentLayout.setBackgroundColor(Color.TRANSPARENT)
                mBinding.root.setBackgroundColor(Color.TRANSPARENT)
            }

    }

    fun releaseWeb() {
        mBinding.llContent.removeAllViews()
        mAgentWeb?.clearWebCache()
        mAgentWeb?.webLifeCycle?.onDestroy()
        mAgentWeb = null
    }

    fun walletUpdate(userId: Long) {
        nativeBridge?.walletUpdate(userId)
    }

    fun onBalanceUpdate(coins: Long) {
        yomiNativeBridge?.onBalanceUpdate(coins)
    }

    /**

     * 语⾔类型类型值
     * 中⽂s    tring 0
     * 繁体中⽂  string 1
     * 英⽂    string   2
     * 印尼语   string   3
     * ⻢来语   string   4
     * 泰语     string   5
     * 越南语   string   6
     * 阿拉伯语  string   7
     * 菲律宾语  string   8
     * 葡萄⽛语  string   9
     * ⼟⽿其语  string   10
     * 乌尔都语  string   11
     * ⽇语     string   12
     * 俄语     string   13
     * 西班⽛语  string   14
     */
    fun getLanguages(providerType: Long? = null): String {
        val la = MultiLanguages.getAppLanguage()

        if (providerType == AppConst.GameType.YOMI) {
            when (la.language) {
                "ar" -> {
                    return "2"
                }

                "tr" -> {
                    return "3"
                }

                else -> {
                    return "1"
                }
            }
        } else {
            when (la.language) {
                "zh" -> {
                    if (la.country.contains("CN")) {
                        return "0"
                    } else if (la.country.contains("HK") || la.country.contains("TW")) {
                        return "1"
                    } else {
                        return "0"
                    }
                }

                "en" -> {
                    return "2"
                }

                "ar" -> {
                    return "7"
                }

                "pt" -> {
                    return "9"
                }

                "ja" -> {
                    return "12"
                }

                "ko" -> {
                    return "2"
                }

                "es" -> {
                    return "14"
                }

                "ms" -> {
                    return "4"
                }

                "tr" -> {
                    return "10"
                }

                "hi" -> {
                    return "3"
                }

                "vi" -> {
                    return "6"
                }

                else -> {
                    return "2"
                }
            }
        }
    }

    private fun isYomiGame(providerType: Long) = providerType == AppConst.GameType.YOMI

    private fun setWebSettings(settings: WebSettings) {
        settings.apply {
            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            // 设置⽀持 Javascript
            javaScriptEnabled = true
            // 设置默认⽂本编码
            defaultTextEncodingName = "UTF-8"
            // 设置可访问本地⽂件
            allowFileAccess = true
            // 设置允许通过 file url 加载的Javascript 读取全部资源 ( 包括⽂件 ,http,https)
            allowFileAccessFromFileURLs = true
            // 设置优先加载缓存
            cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
            // 设置启⽤ HTML5 DOM storage
            domStorageEnabled = true
            // 设置开启数据库缓存
            databaseEnabled = true
            databasePath = context.applicationContext.filesDir.absolutePath
            // 设置⽀持缩放
            setSupportZoom(true)
            // 设置⾃适应
            useWideViewPort = true
            // 设置⾃动播放媒体
            mediaPlaybackRequiresUserGesture = false
            // 设置 5.0 以上允许加载 http 和 https 混合的⻚⾯
            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
    }

    private val mWebChromeClient = object : com.just.agentweb.WebChromeClient() {
        override fun onReceivedTitle(view: WebView, title: String) {
            super.onReceivedTitle(view, title)

        }
    }

    private val webViewClient = object : com.just.agentweb.WebViewClient() {

        @Deprecated("deprecated")
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            if (SystemUtils.isSdkInt24()) {
                return super.shouldOverrideUrlLoading(view, url)
            }
            return if (processUrl(view, url)) {
                true
            } else {
                super.shouldOverrideUrlLoading(view, url)
            }
        }

        override fun shouldOverrideUrlLoading(
            view: WebView,
            request: WebResourceRequest,
        ): Boolean {
            val url = request.url.toString()

            LogExt.logI("--net", url)

            return if (processUrl(view, url)) {
                true
            } else {
                super.shouldOverrideUrlLoading(view, request)
            }
        }

        private fun processUrl(view: WebView, url: String): Boolean {
            if (url.isNotEmpty() && url.startsWith(RouterUtils.Type.KEY_NATIVE)) {
                if (url == RouterUtils.Type.KEY_ACTION + "finish") {
//                    finish()
                    return true
                }
                RouterUtils.routerGoto(url)
                return true
            }

            return false
        }

        override fun shouldInterceptRequest(
            view: WebView,
            request: WebResourceRequest,
        ): WebResourceResponse? {
            return WebViewCacheInterceptorInst.getInstance().interceptRequest(request)
        }

        override fun shouldInterceptRequest(view: WebView, url: String): WebResourceResponse? {
            return WebViewCacheInterceptorInst.getInstance().interceptRequest(url)
        }
    }

    fun onPause() {
        mAgentWeb?.webLifeCycle?.onPause()
    }

    fun onResume() {
        mAgentWeb?.webLifeCycle?.onResume()
    }

    fun onDestroy() {
        mAgentWeb?.webLifeCycle?.onDestroy()
    }

}